package net.wicp.tams.common.os.pool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.pool2.KeyedPooledObjectFactory;
import org.apache.commons.pool2.PooledObject;

import net.wicp.tams.common.Conf;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.beans.Host;

public class SSHFactoryByKey implements KeyedPooledObjectFactory<Host, SSHConnection> {

	private Map<Host, SSHFactory> allFactory = new HashMap<>();//采用Map<Host, SSHPool>也不能治理连接泄漏
	private final List<Host> hostList = new ArrayList<>();

	public SSHFactoryByKey(List<Host> conf) {
		if(conf!=null) {
			hostList.addAll(conf);
		}		
	}

	public void addHost(Host key) {
		this.hostList.add(key);
	}

	@Override
	public PooledObject<SSHConnection> makeObject(Host key) throws Exception {
		if (!allFactory.containsKey(key)) {
			synchronized (SSHFactoryByKey.class) {
				if (!allFactory.containsKey(key)) {
					int indexOf = hostList.indexOf(key);
					if (indexOf < 0) {
						indexOf = hostList.size();
						hostList.add(key);
					}
					Host host = hostList.get(indexOf);// 可能传入只设置了ip和端口的key过来
					SSHFactory fat = new SSHFactory(host.getHostIp(), host.getPort(),
							StringUtil.hasNull(host.getUserName(), Conf.get("common.os.ssh.username")),
							StringUtil.hasNull(host.getPassword(), Conf.get("common.os.ssh.pwd")));
					allFactory.put(host, fat);
				}
			}
		}
		PooledObject<SSHConnection> makeObject = allFactory.get(key).makeObject();
		return makeObject;
	}

	@Override
	public void destroyObject(Host key, PooledObject<SSHConnection> p) throws Exception {
		allFactory.get(key).destroyObject(p);

	}

	@Override
	public boolean validateObject(Host key, PooledObject<SSHConnection> p) {
		return allFactory.get(key).validateObject(p);
	}

	@Override
	public void activateObject(Host key, PooledObject<SSHConnection> p) throws Exception {
		allFactory.get(key).activateObject(p);

	}

	@Override
	public void passivateObject(Host key, PooledObject<SSHConnection> p) throws Exception {
		allFactory.get(key).passivateObject(p);
	}

}
